<template>
  <a-drawer
    :visible="visible"
    class="custom-class"
    :title="title"
    placement="right"
    @close="btnClose"
    :keyboard="false"
    :width="$store.getters.isMobile ? 320 : 800"
    :body-style="{
      height: 'calc(100% - 60px)',
      boxSizing: 'border-box',
      overflowY: 'auto',
    }"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      @finish="btnOk"
      layout="vertical"
    >
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="姓名" name="name">
            <a-input v-model:value="formData.name" placeholder="请输入姓名" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="手机号" name="phone">
            <a-input
              v-model:value="formData.phone"
              placeholder="请输入手机号"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="所属租客" name="owner_id">
            <a-input v-if="ownerInfo.id" :value="ownerInfo.name" disabled />
            <a-select
              v-else
              v-model:value="formData.owner_id"
              show-search
              placeholder="输入租客名称以搜索"
              :default-active-first-option="false"
              :show-arrow="false"
              :filter-option="false"
              :not-found-content="null"
              :options="ownerList"
              @search="handleOwnerInputChange"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="身份" name="type">
            <a-select
              placeholder="请选择身份"
              v-model:value="formData.type"
              :options="optionsType"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="是否是默认联系人" name="is_default">
            <a-radio-group v-model:value="formData.is_default">
              <a-radio :value="1">是</a-radio>
              <a-radio :value="0">否</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="邮箱" name="email">
            <a-input v-model:value="formData.email" placeholder="请输入邮箱" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="证件类型">
            <a-select
              v-model:value="formData.idcard_type"
              :options="cardList"
              placeholder="请选择证件类型"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="证件号码" name="idcard">
            <a-input
              v-model:value="formData.idcard"
              type="Number"
              placeholder="请输入证件号码"
              @blur="idCardInputBlur"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="出生日期">
            <a-input-group compact>
              <a-input
                v-model:value="formData.birth_year"
                style="width: 33%"
                placeholder="请输入年份"
                suffix="年" />
              <a-input
                v-model:value="formData.birth_month"
                placeholder="请输入月份"
                style="width: 33%"
                suffix="月" />
              <a-input
                v-model:value="formData.birth_day"
                placeholder="请输入日"
                style="width: 33%"
                suffix="日" /></a-input-group></a-form-item
        ></a-col>
        <a-col :span="12">
          <a-form-item label="性别" name="sex">
            <a-select
              v-model:value="formData.sex"
              :options="sexList" /></a-form-item
        ></a-col>
        <a-col :span="12" style="margin-bottom: 20px">
          <a-form-item label="状态" name="status">
            <a-select
              v-model:value="formData.status"
              :options="statusList" /></a-form-item
        ></a-col>
        <a-col :span="24">
          <a-form-item>
            <template #label>
              <span>人脸照片</span>
              <text-tip
                :tips="[
                  '用于人脸识别场景，例如人脸门禁。',
                  '照片要求：',
                  '1. 露出额头及耳朵，人脸正面免冠近期大头照；',
                  '2. 照片白底、无逆光、无PS，无过度美颜处理',
                  '3. 照片调整像素为640*480或以上；',
                  '4. 两眼之间的像素点＞60。',
                ]"
              ></text-tip>
            </template>
            <a-upload
              :action="$utils.imgAction"
              :headers="{ 'org-token': $store.getters.token }"
              :multiple="false"
              v-model:file-list="photoList"
              @change="uploadPhoto"
              name="image"
              :data="{ dir: 'org_village_user' }"
              accept="image/jpg,image/jpeg,image/gif,image/png"
              list-type="picture-card"
            >
              <div v-if="photoList.length < 1">
                <PlusOutlined />
              </div>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-row>
      <div class="drawer-footer">
        <a-button class="mr-10" @click.prevent="btnClose">取消</a-button>
        <a-button type="primary" html-type="submit">保存</a-button>
      </div>
    </a-form>
  </a-drawer>
</template>

<script>
import { message } from "ant-design-vue";
import {
  defineComponent,
  reactive,
  ref,
  computed,
  watch,
  toRaw,
  toRefs,
} from "vue";
import request from "../../../common/utils/request";
import { PlusOutlined } from "@ant-design/icons-vue";
import { TextTip } from "bl-common-vue3";
import {CARD_OPTIONS, SEX_OPTIONS} from "@/common/utils/constant";

export default defineComponent({
  name: "HouseholdEdit",
  components: { PlusOutlined, TextTip },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: 0,
    },
    ownerInfo: {
      type: Object,
      default: () => ({
        id: 0,
        name: "",
      }),
    },
  },
  setup(props, context) {
    const title = computed(() => (props.id ? "编辑" : "添加") + "租客联系人");

    const formRef = ref();
    const btnClose = () => {
      context.emit("cancel");
    };

    const formData = reactive({
      name: "",
      phone: "",
      type: undefined,
      owner_id: undefined, // 所属租客
      photo: "",
      birth_year: "",
      birth_month: "",
      birth_day: "",
      sex: 1,
      status: 1,
      idcard: "",
      idcard_type: "idcard",
      is_default: 0, // 是否是默认联系人
      email: "",
    });
    const required = [
      {
        required: true,
        message: "必填项",
      },
    ];
    const idCardRule = [
      {
        pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
        message: "你的身份证格式不正确",
      },
    ];
    const rules = ref({
      name: required,
      phone: required,
      owner_id: required,
      type: required,
      email: required,
      idcard: idCardRule,
    });

    watch(
      () => formData.idcard_type,
      (val) => {
        if (val == "idcard") {
          rules.value.idcard = idCardRule;
        } else {
          delete rules.value.idcard;
        }
      }
    );

    const state = reactive({
      optionsType: [],
      ownerList: [], // 租客列表
      ownerInput: "",
      sexList: SEX_OPTIONS,
      statusList: STATUS_OPTIONS,
      cardList: CARD_OPTIONS,
      photoList: [],
    });

    let timeout = null;
    const handleOwnerInputChange = (value) => {
      state.ownerInput = value;
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      timeout = setTimeout(() => {
        getOwnerList();
      }, 800);
    };

    const getOwnerList = () => {
      request
        .get("/org", "/owner/manage", {
          keywords: state.ownerInput,
        })
        .then((res) => {
          state.ownerList = res.list.map((item) => ({
            value: item.id,
            label: item.name,
          }));
        });
    };

    const typeList = () => {
      if (state.optionsType.length) {
        if (!props.id) {
          formData.type = state.optionsType[0].value;
        }
        return;
      }
      request.get("/village", "/user/type/list").then((res) => {
        state.optionsType = res.typeList.map((item) => {
          return {
            value: item.type,
            label: item.info,
          };
        });
        if (!props.id) {
          formData.type = state.optionsType[0].value;
        }
      });
    };

    const uploadPhoto = (info) => {
      let resFileList = [...info.fileList];
      let result = resFileList.slice(-1);
      result = result[0];
      if (result && result.response) {
        if (result.response.code == 1000) {
          formData.photo = result.response.data.fileUrl;
          state.photoList = resFileList;
        } else {
          message.warning(result.response.msg);
        }
      }
    };

    // 编辑详情
    let detail = {};

    const getDetail = () => {
      if (props.id) {
        request
          .get("/village", "/org/user/detail", { id: props.id })
          .then((res) => {
            detail = res.user;
            if (detail.owner_name) {
              state.ownerInput = detail.owner_name;
              getOwnerList();
            }
            setModelRef({
              name: detail.name,
              phone: detail.phone,
              type: detail.type,
              owner_id: detail.owner_id,
              photo: detail.photo,
              birth_year: detail.birth_year,
              birth_month: detail.birth_month,
              birth_day: detail.birth_day,
              sex: detail.sex,
              status: detail.status,
              idcard: detail.idcard,
              idcard_type: detail.idcard_type || undefined,
              is_default: detail.is_default,
              email: detail.email,
            });
            if (detail.photo) {
              state.photoList = [
                {
                  uid: "1",
                  name: detail.photo,
                  status: "done",
                  url: detail.photo,
                },
              ];
            }
          });
      }
      // else {
      // }
    };
    const setModelRef = (state) => {
      for (let key in state) {
        formData[key] = state[key];
      }
    };

    const idCardInputBlur = () => {
      if (formData.idcard_type == "idcard") {
        getBirthdayFromIdCard();
      }
    };

    const getBirthdayFromIdCard = () => {
      let idCard = formData.idcard;
      if (!idCard && idCard.length < 15) {
        return;
      }
      // sex
      if (parseInt(idCard.slice(-2, -1)) % 2 == 1) {
        formData.sex = 1;
      } else {
        formData.sex = 2;
      }
      // birthday
      if (!formData.birth_day) {
        let birthday = "";
        if (idCard.length == 15) {
          birthday = "19" + idCard.substr(6, 6);
        } else if (idCard.length == 18) {
          birthday = idCard.substr(6, 8);
        }
        birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
        if (birthday) {
          formData.birth_year = birthday.slice(0, 4);
          formData.birth_month = birthday.slice(5, 7);
          formData.birth_day = birthday.slice(8, 10);
        }
      }
    };

    //提交
    const btnOk = () => {
      const params = { ...formData, needMsg: true };
      let requestUrl = "/notice/bindOwnerNoticeContact";
      let requestMethod = "post";
      if (props.id) {
        requestUrl = "/notice/contactEdit";
        requestMethod = "put";
        params.id = props.id;
      }
      request[requestMethod]("/org", requestUrl, params).then((res) => {
        message.success(res.msg || "保存成功");
        context.emit("success");
      });
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          typeList();
          getDetail();
          console.log("-----------props", props);
          if (props.ownerInfo.id) {
            setModelRef({
              owner_id: props.ownerInfo.id,
              is_default: 1,
            });
          }
        } else {
          formRef.value.resetFields();
          state.photoList = [];
          formData.birth_year = "";
          formData.birth_month = "";
          formData.birth_day = "";
        }
      }
    );
    return {
      ...toRefs(state),
      handleOwnerInputChange,
      btnClose,
      btnOk,
      formRef,
      rules,
      formData,
      uploadPhoto,
      title,
      idCardInputBlur,
    };
  },
});

const STATUS_OPTIONS = [
  {
    value: 0,
    label: "待审核",
  },
  {
    value: 1,
    label: "已审核",
  },
  {
    value: 4,
    label: "被拒绝",
  },
];
</script>

<style lang="less" scoped>
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
</style>
